<template>
  <div class="videos">
    <div id="playWnd" class="playWnd" :style="setStyle()"></div>


  </div>
</template>

<script>
var oWebControl = null;// 插件对象
var bIE = (!!window.ActiveXObject || 'ActiveXObject' in window);// 是否为IE浏览器
var pubKey = '';

var iLastCoverLeft = 0;
var iLastCoverTop = 0;
var iLastCoverRight = 0;
var iLastCoverBottom = 0;
var initCount = 0;

import { WebControl } from 'web-control';
export default {
  props: {
    // 视频宽度
    videoWidth: {
      type: Number,
      default: 900,

    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: 500,

    },
    // 视频编码
    cameraCode: {
      type: String,
      default: "c81a58296ae1496a9cd863f3f6aaabad",
      require: true
    },
    // 是否销毁视频弹框
    isdestroy: {
      type: Boolean,
      default: false,
      require: true
    }
  },
  data() {
    return {
      // 初始化
      appkey: '22524585',
      secret: 'vle3qAjdtvvj9DBNtREi',
      ip: '59.32.29.130',
      isHttps: '1',
      port: '89',
      snapDir: 'd:\\SnapDir',
      videoDir: 'd:\\VideoDir',
      layout: '1x1',
      encryptedFields: ['secret'],
      // 布局
      setlayout: '1x1',
      // 预览
      PlayType: '0',
      playWnds: [],
      playWndId: '',
      cameraIndexCode: '',
      streamMode: '0',
      transMode: '1',
      gpuMode: '0',
      // 抓图
      SnapType: '0',
      snapWnds: [],
      snapWndId: '',
      snapName: 'd:\\SnapDir\\test.jpg',
      // 字符叠加
      SetOSDType: '0',
      osdWnds: [],
      osdWndId: '',
      Xsite: '0',
      Ysite: '0',
      RColor: '255',
      GColor: '0',
      BColor: '0',
      OSDText: ''
    }
  },
  watch: {
    isHttps: 'updatePort',
    PlayType: 'UpdatePlayTypeValue',
    SetOSDType: 'UpdateSetOSDTypeValue',
    SnapType: 'UpdateSnapTypeValue',
    isdestroy: {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        if (newVal == true) {
          oWebControl.JS_DestroyWnd()
            .then((data) => {
              console.log("销毁窗口成功");
            })
            .catch((err) => {
              console.log("销毁窗口失败");
            });

        }

      }, deep: true,
      immediate:true,
    }

  },
  created() {
    // 赋值code
    this.cameraIndexCode = this.cameraCode;
  },
  mounted() {
    console.log(this.$props.videoWidth, this.$props.videoHeight);
    // 标签关闭
    window.addEventListener('upload', () => {
      // 此处请勿调反初始化
      if (oWebControl != null) {
        oWebControl.JS_Disconnect().then(() => { }, () => { });
      }
    });

    // 窗口resize
    window.addEventListener('resize', () => {
      if (oWebControl != null) {
        oWebControl.JS_Resize(this.$props.videoWidth, this.$props.videoHeight);
        this.setWndCover();
      }
    });

    // 滚动条scroll
    window.addEventListener('scroll', () => {
      if (oWebControl != null) {
        oWebControl.JS_Resize(this.$props.videoWidth, this.$props.videoHeight);
        this.setWndCover();
      }
    });

    this.initPlugin();

  },
  methods: {
    setStyle() {
      console.log();
      let obj = {
        width: `${this.$props.videoWidth}px`,
        height: `${this.$props.videoHeight}px`,

      }
      return obj
    },
    updatePort() {
      this.isHttps === '1' ? this.port = '443' : this.port = '80'
    },

    UpdatePlayTypeValue() {
      if (this.PlayType === '2') {
        //获取布局，并显示标签和窗口选择下拉框
        document.getElementById("PreviewWndId").style.display = "";//显示
        oWebControl.JS_RequestInterface({
          funcName: "getLayout"
        }).then((oData) => {
          //分析窗口数
          //{"errorCode":0,"errorModule":0,"responseMsg":{"code":0,"data":"{\n    \"layout\": \"2x2\",\n    \"wndNum\": 4\n}\n"},"sequence":"93298475-03d0-49c9-bc3a-a94ec696f983","uuid":"{c76078b4-4f19-4198-b68d-83df1d3d71a9}"}

          //"{\n    \"layout\": \"2x2\",\n    \"wndNum\": 4\n}\n"
          var Data = JSON.stringify(oData.responseMsg.data);
          //"{    \"layout\": \"2x2\",    \"wndNum\": 4}"
          Data = Data.replace(/\\n/g, "");
          //"{    "layout": "2x2",    "wndNum": 4}"
          Data = Data.replace(/\\/g, "");
          //{    "layout": "2x2",    "wndNum": 4}"
          Data = Data.replace(/\"{/g, "{");
          //{    "layout": "2x2",    "wndNum": 4}"
          Data = Data.replace(/}\"/g, "}");
          var DataNum = JSON.parse(Data).wndNum;

          this.createSelectOption(DataNum);
        });
      }
      else {
        //隐藏标签和窗口选择下拉框
        document.getElementById("PreviewWndId").style.display = "none";//隐藏
      }
    },

    createSelectOption(wndNum) {
      this.operate.playWndId = '1';
      this.operate.playWnds = [];
      for (var i = 0; i < wndNum; i++) {
        this.operate.playWnds.push({ 'value': String(i + 1) });
      }
    },

    UpdateSnapTypeValue() {
      if (this.SnapType === '1') {
        //获取布局，并显示标签和窗口选择下拉框
        document.getElementById("SnapShotWndId").style.display = "";//显示
        oWebControl.JS_RequestInterface({
          funcName: "getLayout"
        }).then((oData) => {
          //分析窗口数
          var Data = JSON.stringify(oData.responseMsg.data);
          Data = Data.replace(/\\n/g, "");
          Data = Data.replace(/\\/g, "");
          Data = Data.replace(/\"{/g, "{");
          Data = Data.replace(/}\"/g, "}");
          var DataNum = JSON.parse(Data).wndNum;

          this.createSnapSelectOption(DataNum);
        });
      } else {
        //隐藏标签和窗口选择下拉框
        document.getElementById("SnapShotWndId").style.display = "none";//隐藏
      }
    },

    createSnapSelectOption(wndNum) {
      this.operate.snapWndId = '1';
      this.operate.snapWnds = [];
      for (var i = 0; i < wndNum; i++) {
        this.operate.snapWnds.push({ 'value': String(i + 1) });
      }
    },

    UpdateSetOSDTypeValue() {
      if (this.SetOSDType === '1') {
        //获取布局，并显示标签和窗口选择下拉框
        document.getElementById("SetOSDWndId").style.display = "";//显示
        oWebControl.JS_RequestInterface({
          funcName: "getLayout"
        }).then((oData) => {
          //分析窗口数
          var Data = JSON.stringify(oData.responseMsg.data);
          Data = Data.replace(/\\n/g, "");
          Data = Data.replace(/\\/g, "");
          Data = Data.replace(/\"{/g, "{");
          Data = Data.replace(/}\"/g, "}");
          var DataNum = JSON.parse(Data).wndNum;

          this.createSetOSDSelectOption(DataNum);
        });
      } else {
        //隐藏标签和窗口选择下拉框
        document.getElementById("SetOSDWndId").style.display = "none";//隐藏
      }
    },

    createSetOSDSelectOption(wndNum) {
      this.operate.osdWndId = '1';
      this.operate.osdWnds = [];
      for (var i = 0; i < wndNum; i++) {
        this.operate.osdWnds.push({ 'value': String(i + 1) });
      }
    },



    // 设置窗口遮挡
    setWndCover() {
      var iWidth = document.body.clientWidth;
      var iHeight = document.body.clientHeight;
      var oDivRect = document.getElementById("playWnd").getBoundingClientRect();

      var iCoverLeft = (oDivRect.left < 0) ? Math.abs(oDivRect.left) : 0;
      var iCoverTop = (oDivRect.top < 0) ? Math.abs(oDivRect.top) : 0;
      var iCoverRight = (oDivRect.right - iWidth > 0) ? Math.round(oDivRect.right - iWidth) : 0;
      var iCoverBottom = (oDivRect.bottom - iHeight > 0) ? Math.round(oDivRect.bottom - iHeight) : 0;

      iCoverLeft = (iCoverLeft > 700) ? 700 : iCoverLeft;
      iCoverTop = (iCoverTop > 400) ? 400 : iCoverTop;
      iCoverRight = (iCoverRight > 700) ? 700 : iCoverRight;
      iCoverBottom = (iCoverBottom > 400) ? 400 : iCoverBottom;

      if (iLastCoverLeft != iCoverLeft) {
        console.log("iCoverLeft: " + iCoverLeft);
        iLastCoverLeft = iCoverLeft;
        oWebControl.JS_SetWndCover("left", iCoverLeft);
      }
      if (iLastCoverTop != iCoverTop) {
        console.log("iCoverTop: " + iCoverTop);
        iLastCoverTop = iCoverTop;
        oWebControl.JS_SetWndCover("top", iCoverTop);
      }
      if (iLastCoverRight != iCoverRight) {
        console.log("iCoverRight: " + iCoverRight);
        iLastCoverRight = iCoverRight;
        oWebControl.JS_SetWndCover("right", iCoverRight);
      }
      if (iLastCoverBottom != iCoverBottom) {
        console.log("iCoverBottom: " + iCoverBottom);
        iLastCoverBottom = iCoverBottom;
        oWebControl.JS_SetWndCover("bottom", iCoverBottom);
      }
    },

    // 初始化插件
    initPlugin() {


      oWebControl = new WebControl({
        szPluginContainer: "playWnd",
        iServicePortStart: 15900,
        iServicePortEnd: 15909,
        cbConnectSuccess: () => {

          this.setCallbacks();


          oWebControl.JS_StartService("window", {
            dllPath: "./VideoPluginConnect.dll"
            // dllPath: "./DllForTest-Win32.dll"
          }).then(() => {
            oWebControl.JS_CreateWnd("playWnd", this.$props.videoWidth, this.$props.videoHeight).then(() => {
              console.log("初始化插件成功");
              this.init();
            });
          }, () => {

          });
        },
        cbConnectError: () => {
          console.log("cbConnectError");
          window.location.href = "https://dadingkunag.oss-cn-shenzhen.aliyuncs.com/upload/VideoWebPlugin.exe"
          oWebControl = null;
       
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++; 
          if (initCount < 3) {
            setTimeout(() => {
              this.initPlugin();
            }, 3000)
          } else {
            document.getElementById("playWnd").innerHTML = "插件启动失败，请检查插件是否安装！";
          }
        },
        cbConnectClose: () => {
          console.log("cbConnectClose");
          oWebControl = null;
        }
      });
      console.log(oWebControl);
    },



    // 获取公钥
    getPubKey(callback) {
      oWebControl.JS_RequestInterface({
        funcName: "getRSAPubKey",
        argument: JSON.stringify({
          keyLength: 1024
        })
      }).then((oData) => {
        console.log(oData)
        if (oData.responseMsg.data) {
          pubKey = oData.responseMsg.data
          callback()
        }
      })
    },

    // 设置窗口控制回调
    setCallbacks() {
      oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: this.cbIntegrationCallBack
      });
    },

    // 推送消息
    cbIntegrationCallBack(oData) {
      console.log(oData);
      this.showCBInfo(JSON.stringify(oData.responseMsg));
    },
    // RSA加密
    setEncrypt(value) {
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey(pubKey);
      return encrypt.encrypt(value);
    },

    // 初始化
    init() {
      this.getPubKey(() => {
        var appkey = this.appkey;
        var secret = this.secret;
        var ip = this.ip;
        var szPort = this.port;
        var snapDir = this.snapDir;
        var videoDir = this.videoDir;
        var layout = this.layout;
        var encryptedFields = this.encryptedFields;
        var enableHttps = parseInt(this.isHttps);

        if (!appkey) {
          this.showCBInfo("appkey不能为空！", 'error');
          return
        }
        if (!secret) {
          this.showCBInfo("secret不能为空！", 'error');
          return
        }
        if (!ip) {
          this.showCBInfo("ip不能为空！", 'error');
          return
        }
        if (!szPort) {
          this.showCBInfo("端口不能为空！", 'error');
          return
        } else if (!/^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/.test(szPort)) {
          this.showCBInfo("端口填写有误！", 'error');
          return
        }

        appkey = appkey.replace(/(^\s*)/g, "");
        appkey = appkey.replace(/(\s*$)/g, "");

        secret = this.setEncrypt(secret);
        secret = secret.replace(/(^\s*)/g, "");
        secret = secret.replace(/(\s*$)/g, "");

        ip = ip.replace(/(^\s*)/g, "");
        ip = ip.replace(/(\s*$)/g, "");

        szPort = szPort.replace(/(^\s*)/g, "");
        szPort = szPort.replace(/(\s*$)/g, "");

        snapDir = snapDir.replace(/(^\s*)/g, "");
        snapDir = snapDir.replace(/(\s*$)/g, "");

        videoDir = videoDir.replace(/(^\s*)/g, "");
        videoDir = videoDir.replace(/(\s*$)/g, "");
        var port = parseInt(szPort);

        var argument = {
          appkey: appkey,
          secret: secret,
          ip: ip,
          playMode: 0, // 预览
          port: port,
          snapDir: snapDir,
          videoDir: videoDir,
          layout: layout,
          enableHTTPS: enableHttps
        }

        encryptedFields.map((field) => {
          // secret固定加密，appkey和ip根据用户勾选加密
          if (field === 'ip') {
            argument.ip = this.setEncrypt(ip)
          }
          if (field === 'appkey') {
            argument.appkey = this.setEncrypt(appkey)
          }
          if (field === 'snapDir') {
            argument.snapDir = this.setEncrypt(snapDir)
          }
          if (field === 'videoDir') {
            argument.videoDir = this.setEncrypt(videoDir)
          }
          if (field === 'layout') {
            argument.layout = this.setEncrypt(layout)
          }
        })
        argument.encryptedFields = encryptedFields.join(",");
        oWebControl.JS_RequestInterface({
          funcName: "init",
          argument: JSON.stringify(argument)
        }).then((oData) => {
          this.startPreview();
          this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
        });
      })
    },

    //设置当前布局
    setLayout() {
      var layout = this.setlayout;

      oWebControl.JS_RequestInterface({
        funcName: "setLayout",
        argument: JSON.stringify({
          layout: layout
        })
      }).then((oData) => {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
        this.UpdatePlayTypeValue();
        this.UpdateSnapTypeValue();
        this.UpdateSetOSDTypeValue();
      });
    },

    //获取当前布局
    getLayout() {
      oWebControl.JS_RequestInterface({
        funcName: "getLayout"
      }).then((oData) => {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
        this.UpdatePlayTypeValue();
        this.UpdateSnapTypeValue();
        this.UpdateSetOSDTypeValue();
      });
    },

    //抓图
    previewSnap() {
      var snapName = this.snapName;
      snapName = snapName.replace(/(^\s*)/g, "");
      snapName = snapName.replace(/(\s*$)/g, "");
      var wndId = 0; //选中窗口抓图	
      if (this.SnapType === '1') { //指定窗口抓图
        wndId = parseInt(this.snapWndId, 10);
      } else if (this.SnapType === '0') { //选中窗口抓图
        wndId = 0;
      }

      oWebControl.JS_RequestInterface({
        funcName: "snapShot",
        argument: JSON.stringify({
          name: snapName,
          wndId: wndId
        })
      }).then(function (oData) {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },

    // 视频预览
    startPreview() {
      var cameraIndexCode = this.cameraIndexCode;
      cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, "");
      cameraIndexCode = cameraIndexCode.replace(/(\s*$)/g, "");
      var streamMode = +this.streamMode;
      var transMode = +this.transMode;
      var gpuMode = +this.gpuMode
      var wndId = -1;  //默认为空闲窗口回放
      var v = this.PlayType;

      if (v === '2') { //指定窗口回放
        wndId = parseInt(this.playWndId, 10);
      } else if (v === '1') { //选中窗口回放
        wndId = 0;
      }
      if (!cameraIndexCode) {
        this.showCBInfo("监控点编号不能为空！", 'error');
        return
      }
      oWebControl.JS_RequestInterface({
        funcName: "startPreview",
        argument: JSON.stringify({
          cameraIndexCode: cameraIndexCode,
          streamMode: streamMode,
          transMode: transMode,
          gpuMode: gpuMode,
          wndId: wndId
        })
      }).then((oData) => {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },

    //字符叠加
    setOSDText() {
      var OSDText = this.OSDText;

      var Xsite = parseInt(this.Xsite);
      var Ysite = parseInt(this.Ysite);
      var ColorR = parseInt(this.ColorR);
      var ColorG = parseInt(this.ColorG);
      var ColorB = parseInt(this.ColorB);
      var Color = 65536 * ColorB + 256 * ColorG + ColorR;
      var wndId = 0;

      console.log(OSDText, Xsite, Ysite, Color)

      if (this.SetOSDType === '1') {//指定窗口字符叠加
        wndId = parseInt(this.osdWndId, 10);
      } else { //空闲窗口字符叠加
        wndId = 0;
      }

      oWebControl.JS_RequestInterface({
        funcName: "drawOSD",
        argument: JSON.stringify({
          text: OSDText,
          x: Xsite,
          y: Ysite,
          color: Color,
          wndId: wndId
        })
      }).then(function (oData) {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },

    // 停止预览
    stopAllPreview() {
      oWebControl.JS_RequestInterface({
        funcName: "stopAllPreview"
      }).then((oData) => {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },

    // 反初始化
    uninit() {
      oWebControl.JS_RequestInterface({
        funcName: "uninit"
      }).then((oData) => {
        this.showCBInfo(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },

    // 显示回调信息
    showCBInfo(szInfo, type) {
      if (type === 'error') {
        szInfo = "<div style='color: red;'>" + this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
      } else {
        szInfo = "<div>" + this.dateFormat(new Date(), "yyyy-MM-dd hh:mm:ss") + " " + szInfo + "</div>";
      }
      // document.getElementById("cbInfo").innerHTML += szInfo;
    },

    clear() {
      document.getElementById("cbInfo").innerHTML = "";
    },

    // 格式化时间
    dateFormat(oDate, fmt) {
      var o = {
        "M+": oDate.getMonth() + 1, //月份
        "d+": oDate.getDate(), //日
        "h+": oDate.getHours(), //小时
        "m+": oDate.getMinutes(), //分
        "s+": oDate.getSeconds(), //秒
        "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
        "S": oDate.getMilliseconds()//毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    }
    ,
    textbox(obj, min, max) {
      obj.value = obj.value.replace(/[^\d]/g, '');
      if (parseInt(obj.value) == obj.value && parseInt(obj.value) >= min && parseInt(obj.value) <= max) { }
      else {
        if (parseInt(obj.value) < min) {
          obj.value = min;
        }
        if (parseInt(obj.value) > max) {
          obj.value = max;
        }
      }
    }
  },
  destroyed() {
    oWebControl.JS_DestroyWnd()
      .then((data) => {
        console.log("销毁窗口成功");
      })
      .catch((err) => {
        console.log("销毁窗口失败");
      });


  }
}
</script>

<style scoped>
.videos {
  width: 100%;
  height: 100%;
}

.playWnd {


  /* border: 1px solid red; */
}

.cbInfoDiv {
  float: left;
  width: 360px;
  margin-left: 16px;
  border: 1px solid #7F9DB9;
}

.cbInfo {
  height: 200px;
  padding: 5px;
  border: 1px solid #7F9DB9;
  overflow: auto;
  word-break: break-all;
}

.operate {
  margin-top: 24px;
}

.operate::after {
  content: '';
  display: block;
  clear: both;
}

.operate .btns {
  height: 32px;
}

.module {
  float: left;
  width: 340px;
  min-height: 320px;
  margin-left: 16px;
  padding: 16px 8px;
  box-sizing: border-box;
  border: 1px solid #e5e5e5;
}

.module .item {
  margin-bottom: 4px;
}

.module .label {
  width: 150px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 8px;
  text-align: right;
}

.module input[type="text"],
.module select {
  box-sizing: border-box;
  display: inline-block;
  vertical-align: middle;
  margin-left: 0;
  width: 150px;
  min-height: 20px;
}

.module .btn {
  min-width: 80px;
  min-height: 24px;
  margin-top: 16px;
  margin-left: 158px;
}
</style>